<template>
  <div class="save">
    <h1>商品管理 -- {{ buttonText }}</h1>
    <div class="content">
      <div class="form">
        <el-form ref="form" :model="form" label-width="80px">
          <el-form-item label="商品名称">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="商品描述">
            <el-input v-model="form.subtitle"></el-input>
          </el-form-item>

          <el-form-item label="所属分类">
            <el-select v-model="region" placeholder="请选择一级品类">
              <el-option :label="item.name" :value="item.name" v-for="(item, index) in categoryList" :key="index"></el-option>
            </el-select>
            <!-- 二级 -->
            <el-select v-model="value" placeholder="请选择二级品类" v-show="region">
              <el-option :label="item.name" :value="item.name" v-for="(item,index) in secondListId" :key="index"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="商品价格">
            <input v-model="form.price" type="number" class="inp" />元
          </el-form-item>
          <el-form-item label="商品库存">
            <input v-model="form.stock" type="number" class="inp" />件
          </el-form-item>
          <el-form-item label="商品图片">

            <el-upload class="upload-demo" name="upload_file" multiple :limit="3" action="/api/product/upload.do" :on-preview="handlePreview" :before-remove="beforeRemove" :on-success="handleSuccess" :on-exceed="handleExceed" :before-upload="beforeAvatarUpload">
              <img class="image" :src="form.imageHost + form.mainImage" alt="">
              <el-button size="small" type="primary">点击上传</el-button>

            </el-upload>

          </el-form-item>
          <el-form-item label="商品详情" class="save_content">
            <quill-editor v-model="form.detail" :options="editorOption" @change="onEditorChange($event)" class="quill">
            </quill-editor>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="onSubmit">提交</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
// 富文本引入
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import { quillEditor } from "vue-quill-editor";
// 添加接口
import { GoodsAdd, GoodsDetail, getCategory, getSubtype } from "@/utils/API";
export default {
  components: { quillEditor },
  data() {
    return {
      region: "", //一级品类
      value: "", //二级品类
      buttonText: "",
      form: {
        categoryId: 0,
        name: "", //名称
        subtitle: "", //描述
        detail: "", //富文本
        price: "", //价格
        stock: "", //件数
        status: 1, //状态
        subImages: "", //图片
        id: "",
        mainImage: ""
      },
      editorOption: {},
      edit: false, //判断添加编辑的条件
      categoryList: [], //一级品类
      secondListId: [], //二级品类
      idList: [] //一级品类中的id
    };
  },
  methods: {
    onSubmit() {
      this.add();
    },
    // 富文本
    onEditorChange(v) {
      // console.log(v);
    },
    // 上传图片
    handlePreview(file) {
      // console.log(file)
      // 相对地址
      this.form.subImages = file.response.data.uri;
      // console.log(1, this.form.subImages);
    },
    beforeRemove(file, fileList) {
      // console.log(file, fileList)
      return this.$confirm(`确定删除${file.name}`);
    },
    handleSuccess(response, file, fileList) {
      // console.log(response)
      this.form.mainImage = response.data.url;
      // console.log(file)
      // console.log(fileList)
      this.form.subImages = file.response.data.uri;
    },
    handleExceed(files, fileList) {
      // console.log(files)
      this.$message.warning(
        `当前限制选择3个文件，本次选择了${
          files.length
        }个文件,共选择了${files.length + fileList.length}个文件`
      );
    },
    // 限制图片类型及大小
    beforeAvatarUpload(file) {
      // console.log(file)
      // console.log(file.name)
      // 原生js能力   msg文件的后缀名
      let msg = file.name.substring(file.name.indexOf(".") + 1);
      // console.log(msg)
      const extension = msg === "jpg";
      const extension2 = msg === "png";
      // 2M  size 文件的大小
      const size = file.size / 1024 / 1024;
      // console.log(size)

      if (!extension && !extension2) {
        this.$message({
          message: "上传文件只能是 jpg、png格式",
          type: "warning"
        });
      }
      if (size >= 2) {
        this.$message({
          message: "上传文件大小不能超过2MB！",
          type: "warning"
        });
        return;
      }

      return extension || extension2;
    },
    // 添加商品的接口
    add() {
      // console.log(this.from);
      if (!this.edit) {
        //添加
        GoodsAdd(this.form).then(res => {
          console.log(res);
          this.$router.push("/Goods");
        });
      } else {
        //修改
        console.log(this.form);
        GoodsAdd(this.form).then(res => {
          console.log(res);
          this.$router.push("/Goods");
        });
      }
    },
    // 回显
    backShow() {
      GoodsDetail({ productId: this.form.id }).then(res => {
        // console.log(res);
        this.form = {
          categoryId: res.categoryId,
          detail: res.detail,
          imageHost: res.imageHost,
          mainImage: res.mainImage,
          name: res.name,
          price: res.price,
          stock: res.stock,
          subtitle: res.subtitle,
          parentCategoryId: res.parentCategoryId,
          id: res.id
        };
      });
    },
    // 一级品类
    async render() {
      await getCategory({ categoryId: this.form.categoryId }).then(res => {
        this.categoryList = res;
        // console.log(this.categoryList);
      });
      // console.log(this.categoryList);
      this.categoryList.forEach(item => {
        this.idList.push(item.id);
      });
      // 二级品类
      getCategory({ categoryId: this.idList[0] }).then(res => {
        this.secondListId = res;
        // console.log(res.data.data);
      });
    }
  },
  mounted() {
    // 判断更新或添加
    if (this.$route.params.id) {
      this.edit = true;
      this.buttonText = "修改商品";
      // console.log(this.$route.params.id);
      this.form.id = this.$route.params.id;
      this.backShow();
    } else {
      this.buttonText = "添加商品";
    }
    // 一级
    this.render();
  }
};
</script>

<style lang="scss" scoped>
.save {
  width: 100%;
  height: 100%;
  padding-top: 15px;
  padding-left: 20px;

  h1 {
    font-weight: normal;
    font-size: 40px;
  }

  .content {
    margin-top: 10px;

    .form {
      width: 600px;

      .image {
        width: 80px;
        height: 78px;
      }

      .inp {
        width: 200px;
        height: 30px;
        border: none;
        border-radius: 2px;
        margin-right: 5px;
        padding-left: 5px;
      }

      .save_content {
        width: 1000px;
        height: 300px;

        .quill {
          width: 100%;
          height: 200px;
        }

        .quill ::v-deep img {
          width: 50px;
          height: 50px;
        }
      }
    }
  }
}
</style>
